/**
 * 
 */
package x.java.tea;

import java.io.IOException;

/**
 * @author qiangli
 * 
 */
public class State {
	// state / index to id pattern e.g. ${}
	public final static int START = 0;
	public final static int ENTER = 1;
	public final static int LEAVE = 2; //
	// state
	public final static int NORMAL = 3;
	public final static int ABORT = 4; //

	//
	private byte[] idpattern;
	private byte[] idbuf;
	private int pos;
	private int state;
	private String id;
	
	public State(byte[] idpattern, byte[] idbuf) {
		this.idpattern = idpattern;
		this.idbuf = idbuf;
		this.pos = 0;
		this.state = NORMAL;
	}
	
	public int filter(int b) throws IOException {
		switch (state) {
		case NORMAL:
			if (b == idpattern[START]) {
				state = START;
			}
			break;
		case START:
			if (b == idpattern[ENTER]) {
				state = ENTER;
			} else {
				reset();
				return ABORT;
			}
			break;
		case ENTER:
			if (b == idpattern[LEAVE]) {
				id = makeId();
				reset();
				return LEAVE;
			} else {
				idbuf[pos++] = (byte) b;
			}
			break;
		default:
			// unreachable
		}
		return state;
	}
	
	private String makeId() {
		byte[] id = new byte[pos];
		for (int i = 0; i < pos; i++) {
			id[i] = idbuf[i];
		}
		return new String(id);
	}
	
	private void reset() {
		pos = 0;
		state = NORMAL;
	}

	public byte getStart() {
		return idpattern[START];
	}
	
	public String getId() {
		return id;
	}
}
